package com.lagou.lagouservicegateway.filter;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpCookie;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;

/**
 * @Authther: mrwu
 * @date:2021/4/16-04
 * @Description:com.lagou.logougateway.filtrer
 */
//需要注入容器
@Component
public class TokenFilter implements GlobalFilter, Ordered {
    //需要放行的路径，不需要token
    private static final String[] PASSURLS = {"/user/login","/user/register","/code"};
    @Autowired
    RedisTemplate<String,String> redisTemplate;
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //判断是否需要token
        String requestUrl = exchange.getRequest().getPath().value();
        for (int i = 0; i <PASSURLS.length ; i++) {
            if (requestUrl.startsWith(PASSURLS[i])){
                return chain.filter(exchange);
            }
        }
        List<HttpCookie> token = exchange.getRequest().getCookies().get("token");
        ServerHttpResponse response = exchange.getResponse();
        //判断token是否有效
        //从redis中取出数据
        if (token != null) {
            String value = token.get(0).getValue();
            Object o = redisTemplate.opsForValue().get(value);
            if (o == null) {
                token=null;
            }else {
                //重定向
                //设置响应头为重定向
                response.setStatusCode(HttpStatus.SEE_OTHER);
                response.getHeaders().set(HttpHeaders.LOCATION,"http://localhost:8081/static/welcome.html");
                return response.setComplete();
            }
        }
        //重定向到登陆页面
        //设置响应头为重定向
        response.setStatusCode(HttpStatus.SEE_OTHER);
        response.getHeaders().set(HttpHeaders.LOCATION,"http://localhost:8081/static/login.html");
        return response.setComplete();
    }
    @Override
    public int getOrder() {
        return 0;
    }
}
